package com.zyl.javabasic.链表;

/**
 * @author zyl
 * @Description
 * @since 2025/6/23 21:38
 */
class ListNode {
    int val;
    ListNode next;
    ListNode(int val) {
        this.val = val;
    }
}

public class ListNodeNew {


    public static void main(String[] args) {
        ListNode listNode = new ListNode(0);
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        listNode.next = listNode1;
        listNode1.next  = listNode2;
        listNode2.next = listNode3;
        // 打印链表
        printList(listNode);
        ListNode listNode4 = reverseList(listNode);
        printList(listNode4);

    }


    public static ListNode reverseList(ListNode head) {
        ListNode prev = null;    // 前驱节点
        ListNode curr = head;    // 当前节点

        while (curr != null) {
            ListNode nextTemp = curr.next; // 暂存下一个节点
            curr.next = prev;             // 反转指针
            prev = curr;                  // 前驱节点后移
            curr = nextTemp;              // 当前节点后移
        }
        return prev; // 返回新头节点
    }

    // 方法：打印链表
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println(); // 打印完链表后换行
    }
}
